package com.huangfu.learning.javabase.java.reflect;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/7/14
 * Time: 13:46
 * Version: 1.0
 * Description: 操作其他类中的属性
 **/
public class GetClassField {
    public static void main(String[] args) {
        Class<?> clazz = null;
        try {
            clazz = Class.forName("com.huangfu.learning.javabase.java.reflect.Company");
            Object obj = clazz.newInstance();

            // 获取所有属性
            Field[] fields = clazz.getDeclaredFields();
            // 这里是DeclaredField不是Field
            Field field = clazz.getDeclaredField("name");
            field.setAccessible(true);////对所有属性设置访问权限  当类中的成员变量为private时 必须设置此项,即使是final关键字标示过得属性也可以有访问权限
            field.set(obj, "ztesoft");
            System.out.println(field.get(obj));
            System.out.println("---------↓↓↓↓↓↓-------操作数组↓↓↓↓↓↓-------------");
            int[] tmp = {1, 2, 3, 4, 5, 6};
            Class<?> intInstence = tmp.getClass().getComponentType();
            System.out.println("数组类型：" + intInstence.getName());
            System.out.println("数组长度：" + Array.getLength(tmp));
            System.out.println("第一个数组的元素：" + Array.get(tmp, 0));
            Array.set(tmp, 0, 200);
            System.out.println("修改之后的第一个数组元素：" + Array.get(tmp, 0));


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}

class Company {
    public Company() {
    }

    public Company(String name) {
        this.name = name;
    }

    public Company(String name, String city) {
        this.name = name;
        this.city = city;
    }

    String name;
    String city;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Company{" +
                "name='" + name + '\'' +
                ", city='" + city + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Company company = (Company) o;
        return Objects.equals(name, company.name) &&
                Objects.equals(city, company.city);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, city);
    }
}